﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using KharaPos.Web.Services;

namespace KharaPos.Views.Catalog
{
    public partial class CatalogManagement : Page
    {
        public CatalogManagement()
        {
            InitializeComponent();
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        private void DomainDataSourceLoaded(object sender, LoadedDataEventArgs e)
        {

            if (e.HasError)
            {
                MessageBox.Show(e.Error.ToString(), "Load Error", MessageBoxButton.OK);
                e.MarkErrorAsHandled();
            }
        }

        private void SaveButtonClick(object sender, RoutedEventArgs e)
        {
            CategoryDomainDataSource.SubmitChanges();
        }

        private void CancelButtonClick(object sender, RoutedEventArgs e)
        {
            CategoryDomainDataSource.Load();
        }

        private void NewButtonClick(object sender, RoutedEventArgs e)
        {
            var newform = new AddCategoryWindow();
            newform.Closed += HandleNewformClosed;
            newform.Show();

        }

        void HandleNewformClosed(object sender, System.EventArgs e)
        {
            var form = (AddCategoryWindow) sender;
            if(form.NewCategory!=null)
            {
                var dc = (CatalogContext) CategoryDomainDataSource.DomainContext;
                dc.Categories.Add(form.NewCategory);
                CategoryDomainDataSource.SubmittedChanges += ReloadChanges;
                CategoryDomainDataSource.SubmitChanges();
            }
        }

        void ReloadChanges(object sender, SubmittedChangesEventArgs e)
        {
            CategoryDomainDataSource.Load();
        }

    }
}
